package com.file.parser;


import com.file.bo.AppGjzwfwYlj;
import com.file.bo.ResponseData;
import com.file.constant.ErrorCode;
import com.file.util.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class AppGjzwfwYljXmlParser {

    public ResponseData<String> parseAppGjzwfwYljXmlToJson(String daId, String filePath) {
        log.info("parseAppGjzwfwYljXmlToJson started, daId:{}, filePath:{}", daId, filePath);
        String json = null;

        try {
            if (filePath.contains("_ylj.xml")) {
                AppGjzwfwYlj.YljQueryResult yljQueryResult = parseAppGjzwfwYljQueryResultXml(filePath);
                json = JsonUtils.convertObjectToJson(yljQueryResult);
            } else if (filePath.contains("_sbk.xml")) {
                AppGjzwfwYlj.SbkInfo YljSbkInfo = parseAppGjzwfwYljSbkInfoXml(filePath);
                json = JsonUtils.convertObjectToJson(YljSbkInfo);
            }

        } catch (Exception e) {
            log.error("OnError|{}||{}|{}|{}|{}", ErrorCode.FILE_PARSE_EXCEPTION.getCode(), daId, "", "", "parseAppGjzwfwYljXmlToJson failed", e);
            return new ResponseData<>(json, ErrorCode.FILE_PARSE_EXCEPTION.getCode(),
                    ErrorCode.FILE_PARSE_EXCEPTION.getMsg());
        }

        log.info("parseAppGjzwfwYljXmlToJson completed, daId:{}, filePath:{}, json:{}", daId, filePath, json);
        return new ResponseData<>(json, ErrorCode.SUCCESS.getCode(), ErrorCode.SUCCESS.getMsg());
    }

    private AppGjzwfwYlj.YljQueryResult parseAppGjzwfwYljQueryResultXml(String filePath) throws Exception {
        AppGjzwfwYlj.YljQueryResult yljQueryResult = new AppGjzwfwYlj.YljQueryResult();
        List<AppGjzwfwYlj.Ylj> yljArrayList = new ArrayList<>();
        yljQueryResult.setYljList(yljArrayList);
        AppGjzwfwYlj.Ylj ylj = null;

        List<String> nodeTextList = getNodeTextList(filePath);
//        System.out.println(nodeTextList);

        String sectionName = "";

        for( String nodeText : nodeTextList) {
            if (StringUtils.equals(nodeText, "对应费款所属期")) {
                sectionName = "对应费款所属期";
                continue;
            } else if (StringUtils.equals(nodeText, "经办地名称")) {
                sectionName = "经办地名称";
                continue;
            } else if (StringUtils.equals(nodeText, "待遇实发金额（元）")) {
                sectionName = "待遇实发金额";
                continue;
            } else if (nodeText.contains("如对查询结果有疑问")) {
                break;
            }

            switch (sectionName) { //NOSONAR
                case "对应费款所属期":
                    ylj = new AppGjzwfwYlj.Ylj();
                    ylj.setPeriod(nodeText);
                    break;
                case "经办地名称":
                    ylj.setInsuranceLocationName(nodeText);
                    break;
                case "待遇实发金额":
                    ylj.setActualBenefitAmount(nodeText);
                    yljArrayList.add(ylj);
                    break;
            }

        }

        return yljQueryResult;
    }

    private AppGjzwfwYlj.SbkInfo parseAppGjzwfwYljSbkInfoXml(String filePath) throws Exception {
        AppGjzwfwYlj.SbkInfo yljSbkInfo = new AppGjzwfwYlj.SbkInfo();
        List<AppGjzwfwYlj.Sbk> sbkList = new ArrayList<>();
        yljSbkInfo.setSbkList(sbkList);

        AppGjzwfwYlj.Sbk sbk = null;

        List<String> nodeTextList = getNodeTextList(filePath);
        String sectionName = "";
        for (String nodeText : nodeTextList) {
            if (nodeText.equals("我的社保卡")) {
                sectionName = "我的社保卡";
                continue;
            } else if (nodeText.equals("社会保障号码")) {
                sectionName = "社会保障号码";
                continue;
            } else if (nodeText.startsWith("参保地")) {
                sectionName = "参保地";
            } else if (nodeText.equals("切换参保地")) {
                continue;
            } else if (nodeText.startsWith("社会保障卡号")) {
                sectionName = "社会保障卡号";
                continue;
            } else if (nodeText.startsWith("社保卡银行账户发卡行")) {
                sectionName = "社保卡银行账户发卡行";
                continue;
            } else if (nodeText.startsWith("社保卡银行账户")) {
                sectionName = "社保卡银行账户";
                continue;
            } else if (nodeText.startsWith("社会保障卡应用状态")) {
                sectionName = "社会保障卡应用状态";
                continue;
            } else if (nodeText.startsWith("发卡地")) {
                sectionName = "发卡地";
                continue;
            } else if (nodeText.contains("如果您在省内多个地市参保过")) {
                break;
            }

            switch (sectionName) { //NOSONAR
                case "我的社保卡":
                    yljSbkInfo.setName(nodeText);
                    break;
                case "社会保障号码":
                    yljSbkInfo.setSocialSecurityNumber(nodeText);
                    break;
                case "参保地":
                    sbk = new AppGjzwfwYlj.Sbk();
                    sbk.setInsuranceLocation(nodeText.substring(3));
                    break;
                case "社会保障卡号":
                    sbk.setSocialSecurityCardNumber(nodeText);
                    break;
                case "社会保障卡应用状态":
                    sbk.setSocialSecurityCardAppStatus(nodeText);
                    break;
                case "发卡地":
                    sbk.setCardIssueLocation(nodeText);
                    sbkList.add(sbk);
                    break;
            }
        }

        return yljSbkInfo;
    }

    public List<String> getNodeTextList(String filePath) throws DocumentException {
        SAXReader reader = new SAXReader();
        Document document = reader.read(new File(filePath));

        return parseNode(document.getRootElement().elements());
    }

    private List<String> parseNode(List<Element> elements) {
        List<String> nodeTextList = new ArrayList<>();
        elements.forEach(element -> {
            String text = element.attributeValue("text");
            if (StringUtils.isNotBlank(text)) {
                nodeTextList.add(text);
            }
            nodeTextList.addAll(parseNode(element.elements()));
        });

        return nodeTextList;
    }

    public static void main(String[] args) throws Exception {
        AppGjzwfwYljXmlParser AppGjzwfwYljXmlParser = new AppGjzwfwYljXmlParser();
        String json = AppGjzwfwYljXmlParser.parseAppGjzwfwYljXmlToJson("daid", "D:\\data\\files\\app-gjzwfw-ylj\\我的社保卡信息页_sbk.xml").getData();
        System.out.println(json);

         json = AppGjzwfwYljXmlParser.parseAppGjzwfwYljXmlToJson("daid", "D:\\data\\files\\app-gjzwfw-ylj\\近三年养老险待遇发放查询结果页_ylj.xml").getData();
        System.out.println(json);
    }

}
